﻿using System.IO;
using System.Net;
using Utils;
using Utils.Extensions;
using System;
using StockAccessors.Interdin.Model;

namespace StockAccessors.Interdin.Engine
{
	internal abstract class PageReader : TimeredEngineBase
	{
		#region Attributes

        private readonly WebItemToAccessorStockConverter _converter;
        private readonly object _listLock;
		
		private int _pagesRead;

		#endregion

		#region Properties

		public CookieContainer Cookies { get; set; }
		public int ContractNumber { get; set; }

        protected WebItemToAccessorStockConverter Converter
        {
            get
            {
                return _converter;
            }
        }

        protected object ListLock
        {
            get
            {
                return _listLock;
            }
        }

		public int PagesRead
		{
			get
			{
				return _pagesRead;
			}
			private set
			{
				if(value != _pagesRead)
				{
					_pagesRead = value;
					base.OnPropertyChanged("PagesRead");
				}
			}
		}

		#endregion

        #region Events

        public event EventHandler ErrorDetected;

        #endregion

        #region Public Methods

		protected PageReader(int refreshRate) : base(refreshRate, "Page Reader")
		{
            _converter = new WebItemToAccessorStockConverter();
            _listLock = new object();
		}

		public override void Start()
		{
			this.PagesRead = 0;
			base.Start();
		}

		protected string ReadPageContents(string url)
		{
			using (HttpWebResponse response = HttpWebRequest2.SendGETRequest(url, Properties.Settings.Default.UserAgent, this.Cookies, Properties.Settings.Default.ReadTimeout))
			{
				using (Stream webStream = response.GetResponseStream())
				{
					this.PagesRead++;
					return webStream.ReadTextResponse(response.CharacterSet);
				}
			}
		}

        protected virtual void OnErrorDetected()
        {
            if (this.ErrorDetected != null)
            {
                this.ErrorDetected(this, EventArgs.Empty);
            }
        }

		#endregion


	}
}
